import { Component, OnDestroy, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { select, Store } from '@ngrx/store';
import { NzMessageService } from 'ng-zorro-antd';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { LyricParseService, SongService } from 'src/app/shared';
import { getCurrentSong, getPlayer } from 'src/app/store/selector/play.selector';
import { StoreActionService } from 'src/app/store/store-action.service';
import { AppStoreModule } from 'src/app/store/store.module';
import { Lyric, LyricLine, Song } from '../entity';

@Component({
  selector: 'app-song-detail',
  templateUrl: './song-detail.component.html',
  styleUrls: ['./song-detail.component.less']
})
export class SongDetailComponent implements OnInit, OnDestroy {

  songDetail: Song;
  songLyricLines: LyricLine[];
  currentSong: Song;

  controlLyric = {
    isExpand: false,
    label: '展开',
    icon: 'down'
  };

  private listenDestory = new Subject<void>();

  constructor(
    private activatedRoute: ActivatedRoute,
    private lyricParseService: LyricParseService,
    private songService: SongService,
    private store$: Store<AppStoreModule>,
    private storeActionService: StoreActionService,
    private msg: NzMessageService
  ) { }

  ngOnInit(): void {
    this.activatedRoute.data.subscribe(
      ({ songDetailModel: [song, lyric] }) => {
        this.songDetail = song;
        this.songLyricLines = this.lyricParseService.parseLyric(lyric);
      });
    this.listenCurrentSong();
  }

  ngOnDestroy(): void {
    this.listenDestory.next();
    this.listenDestory.complete();
  }

  onAddSong(song: Song, isPlay = false): void {
    if (this.canAddSong(this.currentSong, song)) {
      this.songService.getSongList(song).subscribe(
        list => {
          if (list && list.length > 0) {
            this.storeActionService.insertSong(list[0], isPlay);
          } else {
            this.msg.warning('无法播放该歌曲');
          }
        }
      );
    }
  }

  toggleLyric(): void {
    this.controlLyric.isExpand = !this.controlLyric.isExpand;
    if (this.controlLyric.isExpand) {
      this.controlLyric.label = '收起';
      this.controlLyric.icon = 'up';
    } else {
      this.controlLyric.label = '展开';
      this.controlLyric.icon = 'down';
    }
  }


  private listenCurrentSong(): void {
    this.store$.pipe(
      select(getPlayer),
      select(getCurrentSong),
      takeUntil(this.listenDestory))
      .subscribe(song => {
        this.currentSong = song;
      });
  }

  private canAddSong(currentSong: Song, addSong: Song): boolean {
    return !currentSong || currentSong.id !== addSong.id;
  }

}
